from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import urllib2
import base64

class MainPage(webapp.RequestHandler):
    def get(self):
        self.redirect('static/index.html') if not self.request.GET.has_key('url') else self._convert(self.request.GET)
    def post(self):
        self._convert(self.request.GET)
        
    def _convert(self, param):
        f = urllib2.urlopen(param['url'])
        callback = param['callback'] if param.has_key('callback') else None
        content_type = f.info().get('content-type')
        body = base64.b64encode(f.read())
        result = {'uri': 'data:%s;base64,%s' % (content_type, body)}
        self.response.out.write('%s(%s)' % (callback, result) if callback else result)
        

application = webapp.WSGIApplication([('/', MainPage)])

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()